package com.ljfiction.book.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.MyBookBean;
import com.ljfiction.book.Baner.ReadDuanBean;
import com.ljfiction.book.Dialog.IsOrNoDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.AuthShuPingActivity;
import com.ljfiction.book.activitys.LoginActivity;
import com.ljfiction.book.activitys.ReadDuanpingActivity;
import com.ljfiction.book.activitys.UserCenterActivity;
import com.ljfiction.book.adapter.DuanPingAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.myinterface.MyAuthorMessageInterface;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Android on 2017/9/27.
 */

public class MyComplanFragment extends BaseFragment {

    private String bookId;
    private MyAuthorMessageInterface myAuthorMessageInterface;
    private int page = 1;
    private ReadDuanBean readDuanBean;
    private BaseQuickAdapter duanPingAdapter;
    private List<ReadDuanBean.DataBean.ListBean> listbean = new ArrayList<>();
    private Context context;
    private Intent intent;
    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView recycleview;
    private IsOrNoDialog isOrNoDialog;
    private LinearLayout nodata;
    private NoBackgLodDialog noBackgLodDialog;
    private boolean isLoddialog=true;
    private LinearLayout onekayread;
    private TextView num;
    private boolean isreadall=false;
    public static MyComplanFragment newInstance( String bookid) {
        MyComplanFragment newFragment = new MyComplanFragment();
        Bundle bundle = new Bundle();
        bundle.putString("booid", bookid);
        newFragment.setArguments(bundle);
        return newFragment;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.myauthormessage_fragment, null);
        Bundle args = getArguments();
        if (args != null) {
            this.context = getContext();
            this.bookId = args.getString("booid");
        }

        recycleview = view.findViewById(R.id.myauthormessage_fragment_recycle);
        smartRefreshLayout = view.findViewById(R.id.myauthormessage_fragment_refresh);
        nodata = view.findViewById(R.id.myauthormessage_fragment_nodata);
        num=view.findViewById(R.id.myauthormessage_fragment_howmuch);
        onekayread=view.findViewById(R.id.myauthormessage_fragment_onekayread);
        context = getActivity();
        intView();
        intData();
        return view;
    }

    private void intView() {
        recycleview.setAdapter(duanPingAdapter= new BaseQuickAdapter<ReadDuanBean.DataBean.ListBean, BaseViewHolder>(R.layout.author_duanping_item, listbean) {
            @Override
            protected void convert(BaseViewHolder helper, ReadDuanBean.DataBean.ListBean item) {
                helper.setText(R.id.author_message_duan_content_mydanmu,item.getCommentContext())
                        .setText(R.id.author_message_duan_mydanmu_myname,item.getPseudonym())
                        .setText(R.id.author_message_duan_danmubookname,"《"+item.getBookName()+"》 "+item.getChapterName()+"  "+item.getShowText().replaceAll("<LG>[a-zA-Z\\d-]{36}<LG>", "\n").replaceAll("\t", "").replaceAll("&nbsp;", " "))
                        .setText(R.id.author_message_duan_mudanmutime, TimeTool.getTimeAndChange(String.valueOf(item.getCommentDateTime())))
                        .setText(R.id.author_message_duan_selectnumdanmu,String.valueOf(item.getThumbsCount()))
                        .setText(R.id.author_message_duan_myduanpingdengji,"LV" + item.getUserGrade());
                Glide.with(mContext).load(item.getUserHeadPortraitURL()).override(ScreenUtils.getNum(mContext,52),ScreenUtils.getNum(mContext,52)).into((ImageView) helper.getView(R.id.author_message_duan_mydanmu_muimage));
                if (item.getUserSex()==0){
                    ((ImageView) helper.getView(R.id.author_message_duan_mydanmusex)).setImageResource(R.mipmap.sex_n);
                }else {
                    ((ImageView) helper.getView(R.id.author_message_duan_mydanmusex)).setImageResource(R.mipmap.sex_v);
                }
                if (item.getVipGrade()>0){
                    helper.getView(R.id.author_message_duan_isvipimage_danmu).setVisibility(View.VISIBLE);
                }else {
                    helper.getView(R.id.author_message_duan_isvipimage_danmu).setVisibility(View.GONE);
                }
                if (item.getIsthumbs()==1){
                    ((ImageView) helper.getView(R.id.author_message_duan_mydanmudianzanimage)).setImageResource(R.mipmap.good);
                }else {
                    ((ImageView) helper.getView(R.id.author_message_duan_mydanmudianzanimage)).setImageResource(R.mipmap.goodno);
                }
                if (item.getCommentisRed()==1||isreadall){
                    helper.getView(R.id.isread_duan).setVisibility(View.VISIBLE);
                    ((CardView)helper.getView(R.id.author_message_duan_isrea_layout_duan)).setCardBackgroundColor(Color.parseColor("#FCFCFC"));
                    ((CardView)helper.getView(R.id.author_message_duan_isrea_layout_duan)).setCardElevation(0);

                }else {
                    helper.getView(R.id.isread_duan).setVisibility(View.GONE);
                    ((CardView)helper.getView(R.id.author_message_duan_isrea_layout_duan)).setCardBackgroundColor(Color.parseColor("#FFFFFF"));
                }
                helper.addOnClickListener(R.id.author_message_duan_mydanmudianzanimage);
                helper.addOnClickListener(R.id.author_message_duan_mydanmu_muimage);
                helper.addOnClickListener(R.id.author_message_duan_delet_myduanping);
            }
        });
        recycleview.setLayoutManager(new LinearLayoutManager(getContext()));
        recycleview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST));
        duanPingAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (listbean.get(position).getCommentisRed()!=1){
                    myAuthorMessageInterface.todeletCom(3);
                    listbean.get(position).setCommentisRed(1);
                    adapter.notifyDataSetChanged();
                }

                Intent intentdian=new Intent(context, ReadDuanpingActivity.class);
                intentdian.putExtra("uuid", listbean.get(position).getPid());
                intentdian.putExtra("chapteTitle", listbean.get(position).getChapterName());
                intentdian.putExtra("chaptertext", listbean.get(position).getCommentContext());
                intentdian.putExtra("chapterId", listbean.get(position).getChapterId());
                intentdian.putExtra("bookId", bookId);
                intentdian.putExtra("bookName", listbean.get(position).getBookName());
                startActivity(intentdian);
            }
        });
        onekayread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isreadall){
                    showToast("已全部已读");
                    return;
                }
                myAuthorMessageInterface.todeletCom(4);
                isreadall=true;
                duanPingAdapter.notifyDataSetChanged();
            }
        });
        duanPingAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.author_message_duan_mydanmudianzanimage:
                        if (!UserManageBean.isLogin(context)) {
                            return;
                        }
                        OkHttpUtils.post(HttpManager.IP + "/paragraphcomment-GiveThumbs")

                                .params("paragraphcommentid", String.valueOf(listbean.get(position).getId()))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                if (listbean.get(position).getIsthumbs() == 0) {
                                                    listbean.get(position).setIsthumbs(1);
                                                    listbean.get(position).setThumbsCount(listbean.get(position).getThumbsCount() + 1);
                                                    duanPingAdapter.notifyDataSetChanged();
                                                } else {
                                                    listbean.get(position).setIsthumbs(0);
                                                    listbean.get(position).setThumbsCount(listbean.get(position).getThumbsCount() - 1);
                                                    duanPingAdapter.notifyDataSetChanged();
                                                }
                                            }else if (jsonObject.getInt("returnCode") == 400){
                                                Intent intent=new Intent(context, LoginActivity.class);
                                                startActivity(intent);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                        break;
                    case R.id.author_message_duan_mydanmu_muimage:
                        intent = new Intent(context, UserCenterActivity.class);
                        intent.putExtra("userId", String.valueOf(listbean.get(position).getUserId()));
                        startActivity(intent);
                        break;
                    case R.id.author_message_duan_delet_myduanping:
                        isOrNoDialog = new IsOrNoDialog(context, "确定删除这条评论？", true);
                        isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                            @Override
                            public void okClick() {
                                OkHttpUtils.post(HttpManager.IP + "/pcomm-delParagraphcomment")

                                        .params("id", String.valueOf(listbean.get(position).getId()))
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onSuccess(String s, Call call, Response response) {
                                                try {
                                                    JSONObject jsonObject = new JSONObject(s);
                                                    if (jsonObject.getInt("returnCode") == 200) {
                                                        listbean.remove(position);
                                                        duanPingAdapter.notifyDataSetChanged();
                                                    }
                                                    showToast(jsonObject.getString("msg"));
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });
                            }

                            @Override
                            public void closeClick() {

                            }
                        });
                        break;
                }
            }
        });
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (bookId != null) {
                    page++;
                    intData();
                }

            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (bookId != null) {
                    page = 1;
                    listbean.clear();
                    intData();
                }

            }
        });
    }

    private void intData() {
        OkHttpUtils.get(HttpManager.IP + "/pcomm-getParagraphcommentbookid/" + bookId + "/" + page)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        smartRefreshLayout.finishLoadMore();
                        smartRefreshLayout.finishRefresh();
                        Gson gson = new Gson();
                        try {
                            readDuanBean = gson.fromJson(s, ReadDuanBean.class);
                            if (readDuanBean.getReturnCode() == 200) {
                                listbean.addAll(readDuanBean.getData().getList());
                                num.setText("共"+readDuanBean.getData().getTotal()+"条");
                                if (listbean.size() <= 0) {
                                    smartRefreshLayout.setVisibility(View.GONE);
                                    nodata.setVisibility(View.VISIBLE);
                                } else {
                                    smartRefreshLayout.setVisibility(View.VISIBLE);
                                    nodata.setVisibility(View.GONE);
                                }
                                duanPingAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public  MyComplanFragment setLisener(MyAuthorMessageInterface myAuthorMessageInterface){
        this.myAuthorMessageInterface=myAuthorMessageInterface;
        return this;
    }
}
